package org.genntii.warehousesystem.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.genntii.warehousesystem.common.Result;
import org.genntii.warehousesystem.domain.dto.CartDTO;
import org.genntii.warehousesystem.domain.entity.Cart;
import org.genntii.warehousesystem.domain.vo.CartVO;
import org.genntii.warehousesystem.service.CartService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "购物车接口",description = "用于用户对用户车的操作")
@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private CartService cartService;

    @Operation(summary = "加入购物车")
    @PostMapping("/add")
    public Result add(HttpServletRequest request, @RequestBody CartDTO dto){
        int userId = (int) request.getAttribute("id");

        Cart cartExists = cartService.cartExists(userId,dto.getGoodsId());
        if (cartExists != null){
            cartService.setNum(cartExists.getId(),dto.getNum()+cartExists.getNum());
            return Result.success();
        }

        cartService.add(userId,dto.getGoodsId(),dto.getPrice(),dto.getNum());
        return Result.success();
    }

    @Operation(summary = "删除购物车货品")
    @PostMapping("/del")
    @Parameter(name = "id", description = "购物车id", required = true, in = ParameterIn.QUERY)
    public Result del(@RequestParam("id") int id){
        cartService.del(id);
        return Result.success();
    }

    @Operation(summary = "修改购物车货品数量")
    @PostMapping("/setNum")
    @Parameters({
            @Parameter(name = "id",description = "购物车id",required = true,in = ParameterIn.QUERY),
            @Parameter(name = "num",description = "用于修改购物车货品数量",required = true,in = ParameterIn.QUERY)
    })
    public Result setNum(@RequestParam("id")int id,@RequestParam("num")int num){
        cartService.setNum(id,num);
        return Result.success();
    }

    @Operation(summary = "获取用户购物车列表")
    @GetMapping("/showAll")
    public Result<List<CartVO>> showAll(HttpServletRequest request){
        int id = (int) request.getAttribute("id");
        return Result.success(cartService.showAllCart(id));
    }

}
